package com.yunzai.file.config;

import com.yunzai.file.domain.Limits;
import com.yunzai.file.domain.Security;
import com.yunzai.file.domain.Storage;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;

import java.util.List;

@Configuration
@ConfigurationProperties(prefix = "file.upload")
@EnableConfigurationProperties(FileUploadConfig.class)
public class FileUploadConfig {

    // 存储路径配置
    private final Storage storage = new Storage();
    // 大小限制配置
    private final Limits limits = new Limits();
    // 安全配置
    private final Security security = new Security();
    // 允许上传的文件
    private List<String> allowedTypes = List.of("*"); // 默认允许所有类型;

    public Storage getStorage() {
        return storage;
    }

    public Limits getLimits() {
        return limits;
    }

    public Security getSecurity() {
        return security;
    }

    public List<String> getAllowedTypes() {
        return allowedTypes;
    }

    public void setAllowedTypes(List<String> allowedTypes) {
        this.allowedTypes = allowedTypes;
    }

    // 类型转换方法（处理带单位的文件大小）
    public long getMaxSizeInBytes() {
        return parseSize(limits.getMaxSize());
    }

    public long getChunkSizeInBytes() {
        return parseSize(limits.getChunkSize());
    }

    private long parseSize(String size) {
        // 实现单位转换逻辑（示例）
        return size.toUpperCase().endsWith("MB")
                ? Long.parseLong(size.substring(0, size.length()-2)) * 1024 * 1024
                : Long.parseLong(size);
    }

    // 添加通配符匹配方法
    public boolean isMimeTypeAllowed(String mimeType) {
        if (allowedTypes == null || allowedTypes.isEmpty()) return false;

        // 处理通配符（如 image/*）
        return allowedTypes.stream().anyMatch(pattern -> {
            pattern = pattern.trim();
            if (pattern.endsWith("/*")) {
                String mainType = pattern.substring(0, pattern.length() - 2);
                return mimeType.startsWith(mainType + "/");
            }
            return pattern.equalsIgnoreCase(mimeType);
        });
    }
}
